package com.fpx.order.plat.bussiness.plat.ebay.service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fpx.api.bean.order.Order;
import com.fpx.api.bean.order.OrderItem;
import com.fpx.api.bean.request.GetOrderRequest;
import com.fpx.api.bean.response.GetOrderResponse;
import com.fpx.api.service.IEbayService;
import com.fpx.order.plat.bussiness.cache.CacheManage;
import com.fpx.order.plat.bussiness.entity.CustomerShop;
import com.fpx.order.plat.bussiness.entity.OriginOrder;
import com.fpx.order.plat.bussiness.entity.OriginOrderAddress;
import com.fpx.order.plat.bussiness.entity.OriginOrderitem;
import com.fpx.order.plat.bussiness.entity.PullOrderLog;
import com.fpx.order.plat.bussiness.plat.base.IPlatOrderHandler;
import com.fpx.order.plat.bussiness.plat.base.SdkCommonRequestOrderThread;
import com.fpx.order.plat.bussiness.service.log.IPullOrderLogService;
import com.fpx.order.plat.bussiness.service.order.IOriginOrderService;
import com.fpx.order.plat.bussiness.system.CacheConstants;
import com.fpx.order.plat.bussiness.system.PlatConstants;
import com.fpx.order.plat.bussiness.vo.OrderDealResult;
import com.fpx.order.plat.common.utils.DateFormatUtils;
import com.fpx.order.plat.common.utils.DecimalUtils;

/**
 * desc:
 * @author xiangtao(xiangtao@4px.com)
 * @date 2015年12月2日 上午11:19:31
 * @version 1.0
 */
@Component
public class EbayPlatOrderHandler implements IPlatOrderHandler {
	
	private final static Logger LOGGER = Logger.getLogger(EbayPlatOrderHandler.class);
	
	@Autowired
	private IPullOrderLogService pullOrderLogService;
	
	@Autowired
	private IOriginOrderService originOrderService;
	
	@Autowired 
	private CacheManage cacheManage;
	
	@Autowired
	private IEbayService ebayService;
	
	/**
	 * 
	 * <p>Title: getOrderByCustomer</p>
	 * <p>Desc: </p>
	 * @author xiangtao(xiangtao@4px.com)
	 * @date 2015年12月2日 下午1:59:23 
	 * @version 1.0
	 * @param configMap 平台应用信息
	 * @param customer  店铺信息
	 * @param startTime 获取订单的开始时间
	 * @param endTime   获取订单的结束时间
	 * @param isAt      是否手动拉单（0/1）
	 * @return
	 * @throws Exception
	 */
	public List<OrderDealResult> getOrderByCustomer(CustomerShop customer, 
			String startTime, String endTime, int isAt)
			throws Exception {
		//结果
        List<OrderDealResult> orderDealRs = new ArrayList<OrderDealResult>();
        //商家编号
        String cm_id = customer.getCm_id();
        //商铺ID 
        String cs_id = customer.getCs_id();
        //授权码
        String accessToken = customer.getCs_token();
		if(StringUtils.isEmpty(cm_id)){
			LOGGER.info("【EBAY】---该商家不存在 或 cm_id 为空!");
        	throw new RuntimeException("【EBAY】---该商家不存在 或 cm_id 为空!");
		}
		if(StringUtils.isEmpty(cs_id)){
			LOGGER.info("【EBAY】---商家：[" + cm_id + "]- 当前商铺不存在 或cs_id为空!");
        	throw new RuntimeException("【EBAY】---商家：[" + cm_id + "]- 当前商铺不存在 或cs_id为空!");
		}	
        if (!StringUtils.isNotEmpty(accessToken)) {
        	LOGGER.info("【EBAY】---商家：[" + cm_id + "]-商铺ID:["+cs_id+"],accessToken为空!");
        	throw new RuntimeException("【EBAY】---商家：[" + cm_id + "]-商铺ID:["+cs_id+"],accessToken为空!");    
        }
        String reqStartTime = null ;
        String reqEndTime = null ;
        PullOrderLog synTime = null;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //判断拉单类型 0自动拉单 1手动
        if(isAt==0){
       	 	//根据店铺与同步类型获取获取最后同步时间
        	synTime = pullOrderLogService.findLastSyncTime(cm_id, cs_id, PlatConstants.ORDER_SOURCE_EBAY);
           if (null == synTime) {
           	//拉单开始时间提前60分钟
           	reqStartTime = df.format(DateFormatUtils.getCalendarDateTime(60));
           	//拉单结束时间推后30分钟
           	reqEndTime = df.format(DateFormatUtils.getCalendarDateTime(-30));
           } else {
           	//请求时间提前30分钟
           	reqStartTime = df.format(DateFormatUtils.getMoveAfterDate("yyyy-MM-dd HH:mm:ss",synTime.getPull_date_end(), -30));
           	reqEndTime = df.format(DateFormatUtils.getSysDateTime());
           	//时间跨度不能超过20天,设置时间
               Calendar cal = Calendar.getInstance();
               cal.setTime(df.parse(reqEndTime));
               cal.add(Calendar.DATE, -20);
               Date miniStartDate = cal.getTime();
               if(df.parse(reqStartTime).getTime() < miniStartDate.getTime()){
               	reqStartTime = df.format(miniStartDate);
               }
           }
       }else if(isAt == 1){
       	reqStartTime = startTime;
       	reqEndTime = endTime;
       }
        Date reqStartD=reqStartTime!=null?
        		df.parse(reqStartTime):DateFormatUtils.getCalendarDateTime(60);
        Date reqEndD=reqEndTime!=null?
        		df.parse(reqEndTime):DateFormatUtils.getCalendarDateTime(-30);
      //请求订单数据
       GetOrderResponse repData = request(customer,reqStartD, reqEndD);
        if(repData==null){
        	return orderDealRs; 
        } 
        //解析订单数据
        List<OriginOrder> orderList = analysisResponse(customer, repData);
        for(OriginOrder orderInfo:orderList){
        	String orderCode=orderInfo.getOrder_code();
    		try{
    			originOrderService.save(orderInfo);
    			orderDealRs.add(new OrderDealResult("0","成功",orderCode));
    			LOGGER.info("【EBAY】---商家：[" + cm_id + "]-商铺ID:["+cs_id+"]-订单号:["+orderCode+"]---保存成功！");
    		}catch(Exception e){
    			LOGGER.error("【EBAY】---商家：[" + cm_id + "]-商铺ID:["+cs_id+"]-订单号:["+orderCode+"]---异常信息:["+e.getMessage()+"]");
    			orderDealRs.add(new OrderDealResult("1",e.getMessage(),orderInfo.getRef_code()));
    		}
    	}
		return orderDealRs;
	}
	
	/**
	 * 
	 * <p>Title: request</p>
	 * <p>Desc: </p>
	 * @author xiangtao(xiangtao@4px.com)
	 * @date 2015年12月2日 下午6:53:33 
	 * @version 1.0
	 * @param customer
	 * @param startDate
	 * @param endDate
	 * @return
	 * @throws Exception
	 */
	public GetOrderResponse request(CustomerShop customer,Date startDate, Date endDate) throws Exception{
		//商铺ID
        String csid = customer.getCs_id();
        //客户号
        String cmid=customer.getCm_id();
        //授权码
        String accessToken = customer.getCs_token();
		
	    startDate = new Date((startDate.getTime() - 60*60*1000 )) ; //往前推60分钟秒
	    endDate = new Date((endDate.getTime() + 30*60*1000 )); //往后推30分钟秒
        //时间跨度不能超过10天,设置时间
        Calendar cal = Calendar.getInstance();
        cal.setTime(endDate);
        cal.add(Calendar.DATE, -10);
        Date miniStartDate = cal.getTime();
        if(startDate.getTime() < miniStartDate.getTime()){
       	 startDate = miniStartDate;
        }
		//request参数封装
		GetOrderRequest request = new GetOrderRequest();
		
		Map<String,String>configMap=
				cacheManage.getPaltSysConfig(CacheConstants.SYSCONFIG_KEY_EBAY);
		request.setConfigMap(configMap);
		//平台类型   ebay
		request.setPlatform(com.fpx.api.util.Constant.PLATFORM_EBAY);
		request.setToken(accessToken);
		//订单的起始时间
		request.setStartDate(startDate);
		//订单的结束时间
		request.setEndDate(endDate);
		
		
		//返回结果
		SdkCommonRequestOrderThread requestThread = new SdkCommonRequestOrderThread(request,PlatConstants.ORDER_SOURCE_EBAY,ebayService);
		new Thread(requestThread).start();
		GetOrderResponse response = requestThread.getResponse();
		if(response==null){
			LOGGER.info("【ebay】拉单请求【超时】,商家:【" + cmid + "】商铺ID:【"+csid+"】");
			return null;
		}
		return response;
	}
	
	public List<OriginOrder> analysisResponse(CustomerShop customer,GetOrderResponse response)throws Exception{
		//存储拆单后的所有订单
		List<OriginOrder> originOrderLst = new ArrayList<OriginOrder>();
		String ack = response.getAck();
		if(ack.equals(com.fpx.api.util.Constant.ACK_SUCCESS)){
			//得到所有的从ebay拉下的订单集合
			List<Order> platOrderList = response.getOrders();
			for(Order platOrder:platOrderList){
				//ebay 平台获取到的订单明细List集合
				List<OrderItem> orders = platOrder.getItems();
				/**
				 *  根据货品种类（sku） 做拆单操作
				 */
				for (int j = 0; j < orders.size(); j++) {
					//订单
					OriginOrder sales = new OriginOrder();
					
					//ebay 平台获取到的订单明细
					OrderItem orderItem = orders.get(j);
					
					//订单货品List集合
					List<OriginOrderitem> orderitems = new ArrayList<OriginOrderitem>();
					
					//订单货品
					OriginOrderitem originOrderitem = new OriginOrderitem();
					
					//订单id改为ItemId +　TransactionId
					String mainOrderNo = orderItem.getItemId()+"-"+orderItem.getTransactionId();
					
					//单据来源
					sales.setPlatform_code(PlatConstants.ORDER_SOURCE_EBAY);
					//平台销售号(ebay)
					sales.setSales_number(platOrder.getSellingManagerSalesRecordNumber());
					//付款时间 
					Date paidTime = platOrder.getPaidTime();
					if(null != paidTime){
						sales.setPayment_time(paidTime);
					}
					// 付款方式=“银行汇款”
					sales.setPayment_method("01");
					// 客户id
					sales.setCustomer_id(customer.getCm_id());
					//客户名下的店铺账号  对应的商铺代码
					sales.setShop_account(customer.getCs_code());//
					// 买家昵称
					sales.setBuyer_id(platOrder.getBuyerId());
					// 平台物流配送方式
					sales.setShipping_service(platOrder.getShippingService());
					// 交易站点ID
					sales.setTransaction_site_id(platOrder.getTransactionSiteId());
					// PAYPAL交易号
					sales.setExternaltransaction(platOrder.getExternalTransactionId());
					
					OriginOrderAddress orderAddress =new OriginOrderAddress();
					
					//收件人姓名
					orderAddress.setConsignee_name(platOrder.getConsigneeName());
					//收件人国家代码 	
					orderAddress.setConsignee_country_code(platOrder.getDestinationCountryCode());
					//收件人国家名称 	
					orderAddress.setConsignee_country_name(platOrder.getDestinationCountryName());
					//收件人州
					orderAddress.setConsignee_stateorprovince(platOrder.getConsigneeState());
					//收件人市
					orderAddress.setConsignee_cityname(platOrder.getConsigneeCity());
					//收件人街道1
					orderAddress.setConsignee_street1(StringUtils.isEmpty(platOrder
							.getConsigneeAddressLine1()) ? platOrder
									.getConsigneeAddressLine2() : platOrder
									.getConsigneeAddressLine1());
					//收件人街道2
					orderAddress.setConsignee_street2(platOrder.getConsigneeAddressLine2());
					
					// 收货人邮编
					orderAddress.setConsignee_postcode(platOrder.getConsigneePostCode());
					// 收货人联系方式
					orderAddress.setConsignee_phone(platOrder.getConsigneePhone());
					// 收货人邮箱 (这里写的买家邮箱)
					sales.setBuyer_email(platOrder.getConsingeeEmail());
					// 卖家paypal邮箱
					sales.setSeller_paypal_email(platOrder.getSellerEmail());
					// 运输成本
					sales.setShipping_service_cost(platOrder.getShippingServiceCost().toString());
					//订单备注
					if (StringUtils.isNotEmpty(platOrder.getNote())) {
						sales.setRemark(platOrder.getNote());
					}
					// 单据状态
					sales.setPfo_os_code(PlatConstants.ORDER_STATUS_NEW);//待处理 状态
//					上传服务商跟踪号(N:未上传;U:上传中;Y:上传成功)
					sales.setUpload_ship_code(PlatConstants.UPLOAD_STATUS_N);//N:未上传
					 // 货品序列(多个货品从1开始累加)
					originOrderitem.setPfoo_item_seq(DecimalUtils.fomatDecimal(j + 1,"000"));
					// 商品ID
					originOrderitem.setItem_code(orderItem.getSku());
					// 商品名称
					originOrderitem.setItem_name(orderItem.getItemTitle());
					// 货品数量
					BigDecimal planQty = new BigDecimal(orderItem.getQuantity() == null ? 0 : orderItem.getQuantity());
					originOrderitem.setQuantity(String.valueOf(planQty));
					
					// 单价(当前销售价格)
					double tprice = DecimalUtils.round(2, orderItem.getPrice() == null ? 0 : orderItem.getPrice());
					BigDecimal price = new BigDecimal(tprice);
					originOrderitem.setCurrent_price(String.valueOf(price));
					
					// 买家实付金额=单价*数量
					BigDecimal paymentSum = price.multiply(planQty);
					double paySum = DecimalUtils.round(2, paymentSum.doubleValue());
					originOrderitem.setPayment_sum(String.valueOf(paySum));
				
					//交易ID
					originOrderitem.setTransaction_id(orderItem.getTransactionId());
					// 货品标识码=子订单号
					originOrderitem.setItem_id(orderItem.getItemId());
					// 币种
					originOrderitem.setCurrency(platOrder.getCurrency());
					
					//拆订单后的 -支付金额
					sales.setAmount_paid(DecimalUtils.round(2, paySum)+"");
					//订单号
					sales.setOrder_code(mainOrderNo);
					//参考单号
					sales.setRef_code(mainOrderNo);
					//创建时间
					sales.setPfo_createdate(new Date());
					//最后修改时间
					sales.setPfo_modifydate(new Date());
					//将地址信息放入订单
					sales.setOrderAddress(orderAddress);
					
					//将订单货品放入集合中  （这个集中始终只有一个货品，因为做了拆单）
					orderitems.add(originOrderitem);
					//订单集合放入订单中
					sales.setOrderitems(orderitems);
					originOrderLst.add(sales);
				}
			}
		}else{
			String failMessage = response.getFailMessage();
			if(failMessage==null){
				failMessage = "null值错误";
			}
			throw new Exception(failMessage);
		}
		return originOrderLst;
	}
	
}
